package com.chinackts.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinackts.common.exception.ApplicationException;
import com.chinackts.common.okhttp.OkHttpRequest;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Lianhong
 * @since 2021/11/3
 * 单一窗口图形验证码识别
 */
public class VerifyCodeSolver {

    //识别单一窗口验证码接口
    private static final String IDENTIFY_VERIFY_CODE_URL = "http://221.226.83.72:4008/captchasolver";

    /**
     * 单一窗口验证码识别
     *
     * @return 验证码
     */
    public static String verifyCode(OkHttpRequest request, byte[] bytes, String nsrsbh, String hgqydm) {
        JSONObject params = new JSONObject() {{
            put("nsrsbh", nsrsbh);
            put("hgqydm", hgqydm);
            put("gifBytes", bytes);
        }};
        String response = request.post(IDENTIFY_VERIFY_CODE_URL, params.toString());
        if (StringUtils.isBlank(response)) verifyCode(request, bytes, nsrsbh, hgqydm);
        JSONObject verifyCodeResp = JSON.parseObject(response);
        if (!verifyCodeResp.containsKey("code")) throw new ApplicationException("9007", "未获取到验证码，请重新尝试采集");
        return verifyCodeResp.getString("code");
    }
}
